package com.vanysoft.business.system.email.service.impl;

import com.vanysoft.business.system.email.service.EmailService;
import com.vanysoft.business.system.email.vo.EmailVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author qi_ma
 */
@Service

public class EmailServiceImpl implements EmailService {
    private final Log log = LogFactory.getLog(getClass());
    @Resource
    private JavaMailSenderImpl mailSender;

    @Override
    public void sendEmail(EmailVo emailVo) {
        if (emailVo.isHtml()) {
            sendPlainMail(emailVo.getTo(), emailVo.getSubject(), emailVo.getContent());
        } else {
            sendHtmlMail(emailVo.getTo(), emailVo.getSubject(), emailVo.getContent());
        }
    }

    /**
     * 发送文本邮件
     *
     * @param to      收件人数组
     * @param subject 主题
     * @param content 内容
     */
    private void sendPlainMail(String[] to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailSender.getUsername());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 发送html格式邮件
     *
     * @param to      收件人数组
     * @param subject 主题
     * @param content 内容
     */
    private void sendHtmlMail(String[] to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常！", e);
        }
    }

}